import asyncio
import argparse
from playwright.async_api import async_playwright

class StudyAutomation:
    def __init__(self, url, browser_executable_path, button_texts):
        """
        初始化学习自动化类

        :param url: 要访问的学习页面URL
        :param browser_executable_path: 浏览器可执行文件路径
        :param button_texts: 要匹配的按钮文本元组
        """
        self.url = url
        self.browser_executable_path = browser_executable_path
        self.button_texts = button_texts

    async def run(self):
        """
        运行自动化学习任务
        """
        async with async_playwright() as p:
            # 启动浏览器
            browser = await p.chromium.launch(
                executable_path=self.browser_executable_path,
                headless=False
            )
            context = await browser.new_context()
            page = await context.new_page()

            await page.goto(self.url)
            print(f"页面打开成功: {self.url}，开始监听弹窗...")
            print(f"监听按钮文本: {'、'.join(self.button_texts)}")

            try:
                while True:
                    try:
                        # 根据传入的按钮文本构建更灵活的选择器
                        selector = ", ".join([f"button:has-text('{text}')" for text in self.button_texts])
                        buttons = await page.locator(selector).all()

                        for button in buttons:
                            if await button.is_visible():
                                button_text = await button.text_content()
                                print(f"检测到弹窗按钮({button_text.strip()})，正在点击...")
                                await button.click()
                                await asyncio.sleep(1)
                    except Exception as e:
                        print("检测弹窗时出错：", e)

                    await asyncio.sleep(2)  # 每2秒检查一次
            finally:
                # 确保最后会关闭浏览器
                await browser.close()

def parse_button_texts(text):
    """将逗号分隔的字符串转换为元组"""
    return tuple(t.strip() for t in text.split("&") if t.strip())

def main():
    # 设置命令行参数解析
    parser = argparse.ArgumentParser(
        description='学习平台自动化脚本，自动处理学习弹窗',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter
    )
    parser.add_argument(
        'url',
        type=str,
        help='要访问的学习页面URL'
    )
    parser.add_argument(
        '--browser-path',
        type=str,
        default=r'C:\Program Files\Google\Chrome\Application\chrome.exe',
        help='本地Chrome浏览器的可执行文件路径'
    )
    parser.add_argument(
        '--buttons',
        type=parse_button_texts,
        default="开始学习&继续学习",
        help='要匹配的按钮文本，多个按钮用"&"符号分隔'
    )

    # 解析参数
    args = parser.parse_args()

    # 创建实例并运行
    automation = StudyAutomation(args.url, args.browser_path, args.buttons)
    asyncio.run(automation.run())

if __name__ == "__main__":
    main()